package com.iflytek.uc.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iflytek.uc.service.ConfigService;
import com.iflytek.uc.vo.Database;

@Controller
@RequestMapping("/admin/system")
public class SystemController {
	
	private static final Logger LOG = Logger.getLogger(SystemController.class);
	
	private static final Database[] DATABASES = new Database[] {
		new Database("h2", 
				"org.h2.Driver", 
				"jdbc:h2:~/.uc/uc2_db;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000", 
				"SELECT 1", 
				"org.hibernate.dialect.H2Dialect"
		),
		new Database("mysql", 
				"com.mysql.jdbc.Driver", 
				"jdbc:mysql://localhost:3306/uc2_db?useUnicode=true&characterEncoding=utf-8", 
				"SELECT 1", 
				"org.hibernate.dialect.MySQL5Dialect"
		),
		new Database("oracle", 
				"oracle.jdbc.driver.OracleDriver", 
				"jdbc:oracle:thin:@localhost:1521:uc2", 
				"SELECT 1 FROM dual", 
				"org.hibernate.dialect.Oracle9iDialect"
		),
		new Database("sqlserver", 
				"com.microsoft.sqlserver.jdbc.SQLServerDriver", 
				"jdbc:sqlserver://localhost;database=uc2_db;",
				"SELECT 1", 
				"org.hibernate.dialect.SQLServerDialect"
		),
	};
	
	private Date serverStartTime = new Date();
	
	@Autowired
	private ConfigService configService;
	
	@RequestMapping("infomation")
	public ModelAndView infomation(HttpServletRequest request) {
		LOG.info("<open system infomation page>");
		
		Properties props = System.getProperties();
		long maxMemory = Runtime.getRuntime().maxMemory();
		long totalMemory = Runtime.getRuntime().totalMemory();
		
		ModelAndView mv = new ModelAndView("/system/infomation");
		
		mv.addObject("serverUrl", getServerUrl(request));
		mv.addObject("host", getHostName());
		mv.addObject("serverStartTime", getServerStartTime());
		
		mv.addObject("osName", props.get("os.name"));
		mv.addObject("osVersion", props.get("os.version"));
		mv.addObject("javaHome", props.get("java.home"));
		mv.addObject("javaRuntimeName", props.get("java.runtime.name"));
		mv.addObject("javaVersion", props.get("java.version"));
		mv.addObject("javaVendor", props.get("java.vendor"));
		mv.addObject("javaVmVersion", props.get("java.vm.version"));
		mv.addObject("maxMemory", maxMemory / 1024 / 1024);
		mv.addObject("totalMemory", totalMemory / 1024 / 1024);
		
		mv.addObject("passwordEncoder", configService.getPasswordEncoder().getClass().getName());
		mv.addObject("authenticationHandler", configService.getAuthenticationHandler().getClass().getName());
		mv.addObject("applicationTitle", configService.getApplicationTitle());
		mv.addObject("rootAccount", configService.getRootAccount());
		
		mv.addObject("databaseType", configService.getDatabaseType());
		mv.addObject("databaseDriver", configService.getDatabaseDriver());
		mv.addObject("databaseUrl", configService.getDatabaseUrl());
		mv.addObject("databaseUsername", configService.getDatabaseUsername());
		mv.addObject("databaseValidation", configService.getDatabaseValidation());
		mv.addObject("hibernateShowSql", configService.getHibernateShowSql());
		mv.addObject("hibernateDialect", configService.getHibernateDialect());
		
		return mv;
	}
	
	@RequestMapping("service")
	public ModelAndView service() {
		LOG.info("<open service config page>");
		
		ModelAndView mv = new ModelAndView("/system/service");
		mv.addObject("passwordEncoder", configService.getPasswordEncoder().getClass().getName());
		mv.addObject("authenticationHandler", configService.getAuthenticationHandler().getClass().getName());
		mv.addObject("applicationTitle", configService.getApplicationTitle());
		mv.addObject("rootAccount", configService.getRootAccount());
		
		return mv;
	}
	
	@RequestMapping("update/service")
	@ResponseBody
	public Map<String, String> service(String passwordEncoder, 
			String authenticationHandler, 
			String applicationTitle, 
			String rootAccount) {
		
		LOG.info("<update service config>");
		Map<String, String> r = new HashMap<String, String>();
		
		try {
			configService.setPasswordEncoderClassName(passwordEncoder);
			configService.setAuthenticationHandlerClassName(authenticationHandler);
			configService.setApplicationTitle(applicationTitle);
			configService.setRootAccount(rootAccount);
			r.put("result", "ok");
		}
		catch (Exception e) {
			r.put("result", "ng");
			r.put("message", e.getMessage());
		}
		return r;
	}
	
	@RequestMapping("database")
	public ModelAndView database() {
		LOG.info("<open database config page>");
		
		ModelAndView mv = new ModelAndView("/system/database");
		mv.addObject("databaseType", configService.getDatabaseType());
		mv.addObject("databaseDriver", configService.getDatabaseDriver());
		mv.addObject("databaseUrl", configService.getDatabaseUrl());
		mv.addObject("databaseUsername", configService.getDatabaseUsername());
		mv.addObject("databasePassword", configService.getDatabasePassword());
		mv.addObject("databaseValidationQuery", configService.getDatabaseValidation());
		mv.addObject("hibernateDialect", configService.getHibernateDialect());
		
		mv.addObject("databases", DATABASES);
		
		return mv;
	}
	
	@RequestMapping("update/database")
	@ResponseBody
	public Map<String, String> database(String databaseType,
			String databaseDriver,
			String databaseUrl,
			String databaseUsername,
			String databasePassword,
			String databaseValidationQuery,
			String hibernateDialect) {
		
		LOG.info("<update database config>");
		Map<String, String> r = new HashMap<String, String>();
		
		try {
			configService.setDatabaseType(databaseType);
			configService.setDatabaseDriver(databaseDriver);
			configService.setDatabaseUrl(databaseUrl);
			configService.setDatabaseUsername(databaseUsername);
			configService.setDatabasePassword(databasePassword);
			configService.setDatabaseValidation(databaseValidationQuery);
			configService.setHibernateDialect(hibernateDialect);
			r.put("result", "ok");
		}
		catch (Exception e) {
			r.put("result", "ng");
			r.put("message", e.getMessage());
		}
		return r;
	}
	
	@RequestMapping("entity")
	public String entity(String entityCategory) {
		//TODO
		return "underConstruction";
	}
	
	@RequestMapping("authorization")
	public String authorization() {
		//TODO
		return "underConstruction";
	}
	
	@RequestMapping("export")
	public String export() {
		//TODO
		return "underConstruction";
	}

	@RequestMapping("import")
	public String import_() {
		//TODO
		return "underConstruction";
	}

	private String getServerStartTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(serverStartTime);
	}

	private String getServerUrl(HttpServletRequest request) {
		String schema = request.getScheme();
		String server = request.getServerName();
		int port = request.getLocalPort();
		String context = request.getContextPath();

		String serverUrl = schema + "://" + server + (port == 80 ? "" : (":" + port)) + context;
		return serverUrl;
	}
	
	private String getHostName() {
		try {
			InetAddress inetAddress = InetAddress.getLocalHost();
			//String ip = inetAddress.getHostAddress();
			String name = inetAddress.getHostName();
			return name;
		}
		catch (UnknownHostException e) {
			return StringUtils.EMPTY;
		}
		
	}

}
